﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using BusinessEntity;
using BusinessService;
using Newtonsoft.Json;

namespace BusinessLogic
{
    public class DeptManager
    {
        DeptService ds = new DeptService();
        public List<Department> GetAllValid()
        {//中原集团/南京中原/三级市场
            var list = ds.GetAllValid();

            return list;
        }

        #region test
        public void SerailDeptList()
        {
            var ArrayOfDepartment = GetAllValid();
            var xmlSerializer = new XmlSerializer(typeof(List<Department>));
            using (var ms = new MemoryStream())
            {
                xmlSerializer.Serialize(ms, ArrayOfDepartment);
                var xmlstring = Encoding.UTF8.GetString(ms.ToArray());
                using (var sw = new StreamWriter("D:\\list.xml"))
                {
                    sw.Write(xmlstring);
                }

            }
        }

        public List<Department> DeserailDeptList()
        {
            using (var sr = new StreamReader(@"D:\projects\New folder\list.xml"))
            {
                var xmlSerializer = new XmlSerializer(typeof(List<Department>));
                using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(sr.ReadToEnd())))
                {
                    using (var xmlreader = XmlReader.Create(ms))
                    {
                        return xmlSerializer.Deserialize(xmlreader) as List<Department>;
                    }
                }
            }
        }

        //public void XMLToDB()
        //{
        //    var list = DeserailDeptList();
        //    var i = 1;
        //    foreach (var department in list)
        //    {
        //        var sql = "insert into department values(@deptid,@fullname,@parentid,@status)";
        //        SqlHelper.ExecuteNonQuery(sql,
        //            new SqlParameter("@deptid", department.DeptId),
        //            new SqlParameter("@fullname",department.FullName),
        //            new SqlParameter("@parentid",department.ParentId),
        //            new SqlParameter("@status",department.Status)
        //            );
        //        Console.WriteLine(i);
        //        i++;
        //    }
        //}

        #endregion

        public int SyncDepartments()
        {
            var remoteDeptList = ds.GetAll(true);
            ds.Truncate();
            var i = 0;
            foreach (var department in remoteDeptList)
            {
                i += ds.AddOne(department);
            }
            return i;
        }

        public List<Department> GetlAll(bool isRemote)
        {
            return ds.GetAll(isRemote);
        }

        /// <summary>
        /// 只获取所有三级市场的架构
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public string SanJiShiChangDeptListToLevelJson(List<Department> list)
        {
            //剔除组
            for (var i = 0; i < list.Count; i++)
            {
                var dptName = list[i].FullName;
                if (dptName.IndexOf("A组") != -1 || dptName.IndexOf("B组") != -1 || dptName.IndexOf("C组") != -1 ||
                    dptName.IndexOf("D组") != -1 ||
                    dptName.IndexOf("E组") != -1 || dptName.IndexOf("组") != -1 || dptName.IndexOf("一组") != -1 ||
                    dptName.IndexOf("二组") != -1)
                {
                    list.Remove(list[i]);
                    i --;
                }
            }
            var rootDepartment = new Department();
            for (var i = 0; i < list.Count; i++)
            {
                Console.WriteLine(list[i].DeptId);
                if (list[i].DeptId.ToLower().Equals("9d7c9355-f21b-40ef-bf10-533f29124ae1"))
                {
                    rootDepartment = list[i];
                    AddChildren(rootDepartment, list);
                }
            }

            //rootDepartment.Children.Insert(0,new Department()
            //{
            //    DeptId="-1",
            //    FullName = "==请选择分行==",
            //});
            var returnjson = JsonConvert.SerializeObject(rootDepartment.Children).Replace("DeptId", "id").Replace("FullName", "text").Replace("Children", "children").Replace("\"children\":null,", "").Replace("\"", "\'").Replace("中原集团/南京中原/三级市场/", "");
            return returnjson;
        }

        /// <summary>
        /// 全部架构
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public string DeptListToLevelJsonCommon(List<Department> list)
        {
            var rootDepartment = new Department();
            for (var i = 0; i < list.Count; i++)
            {
                if (string.IsNullOrEmpty(list[i].ParentId))
                {
                    rootDepartment = list[i];
                    AddChildren(rootDepartment, list);
                }
            }

            var returnjson = JsonConvert.SerializeObject(rootDepartment.Children).Replace("DeptId", "id").Replace("FullName", "text").Replace("Children", "children").Replace("\"children\":null,", "").Replace("\"", "\'").Replace("中原集团/南京中原/三级市场/", "");
            return returnjson;
        }

        private void AddChildren(Department dept, List<Department> list)
        {
            foreach (var item in list)
            {
                if (item.ParentId == dept.DeptId)
                {
                  
                    if(dept.Children == null) dept.Children = new List<Department>();
                    dept.Children.Add(item);
                }
            }
            if (dept.Children == null) return;
            foreach (var item in dept.Children)
            {
                AddChildren(item, list);
            }
        }
    }
}
